define(['app'], function(app) {
	'use strict';

	var GLOBLE = {
		ts: new Date().getTime(),
	}

	var SaveData = null;

	var controller = function controller($scope,$rootScope, $stateParams, Findus, GoDialog, $window, $timeout, $ionicSideMenuDelegate, $ionicLoading, Auth, GoRegion, GoBrandCat, GoMap, GoPage, GoWapAuth) {

		function init_scope() {
			$scope.data = {
				store_issue:"",
				store_issue_select:{id:0,name:"请选择类型"},
				container_stamp: new Date().getTime(),
				// isCenter: false,
				isMemberMap: false,
				isLogin: false,
				isClient: false,

				issue_list: [],
				store_region: {
					package: '',
					data: {
						list1: [],
						value1: '',
						value1_select:{id:0,text:"请选择省份"},
						list2: [],
						value2: '',
						value2_select:{id:0,text:"请选择城市"},
						list3: [],
						value3: '',
						value3_select:{id:0,text:"请选择地区"}
					}
				},

				area: '',
				store_issue: '',
				goods_cat: '',
				store_name: '',
				brand: '',

				point: null,
				location_rs: {},

				store_list: []
			};

			$scope.data.store_cat = {
				cats: [{
					list1: [],
					value1: '',
					value1_select:{id:0,text:"请选择分类"},
					list2: [],
					value2: '',
					value2_select:{id:0,text:"请选择分类"},
					list3: [],
					value3: '',
					value3_select:{id:0,text:"请选择分类"}
				}]
			};

			SaveData = $scope.data;
		}

		//画面加载
		$scope.$on('$ionicView.afterEnter', function(scope, status) {
			//动态设置高度
			// GoPage.init_top($scope, 0, 49);
			// $scope.map_height = Math.floor($window.innerWidth / 2.75);

			//初始加载
			// $scope.init_BMap();

			if(status.direction != 'back') {
				init_scope();

				if($stateParams.center == 'center') {
					$scope.data.isMemberMap = true;
				}

				$rootScope.init_localtion();
			} else {
				$scope.data = SaveData;
				$scope.show_store();
			}
		}, false);

		//定位获取
		$scope.init_maplocaltion = function(cb) {
			//拿到定位session
			//用户拿到定位
			var localsession = Auth.get_session();
			//已经定位了，直接去请求
			if(localsession == undefined) {
				//初始化定位地址
				GoDialog.loading(true, "正在定位操作...");
				GoMap.get_currentlocation(function(point) {
					//获取到百度坐标
					GoDialog.loading(false, "正在定位操作...");
					var params = { longitude: point.lng, latitude: point.lat };
					//内存保存数据
					GoMap.clear_homelocaltion();
					//设置保存
					GoMap.set_homelocaltion({ longitude: point.lng, latitude: point.lat });
					//请求转换
					$scope.get_location(params, function(data) {
						if(data.session != undefined) {
							Auth.save_session(data.session);
						}
						//调用位置
						$scope.data.point = { lng: point.lng, lat: point.lat };
						cb && cb();
					});
				});
			} else {
				//调用位置
				$scope.data.point = { lng: GoMap.get_homelocaltion('longitude'), lat: GoMap.get_homelocaltion('latitude') };
				cb && cb();
			}
		};
		//请求定位
		$scope.get_location = function(params, callback) {
			Findus.get_local({
					longitude: params.longitude,
					latitude: params.latitude
				},
				function(result) {
					if(result.success) {
						//请求成功
						if(callback)
							callback(result.result);
					}
				}
			);
		};
		$scope.init_map = function(cb, init) {
			//执行定位操作
			$scope.init_maplocaltion(cb);
		}

		//下拉刷新 判断哪个模块进行刷新
		$scope.doRefresh = function() {
			$rootScope.init_localtion();
			$timeout(function() {
				$scope.$broadcast('scroll.refreshComplete');
			}, 1);
		};

		//上拉加载更多必须定义
		$scope.isLoad = false;
		//加载更多
		$scope.doRefreshMore = function() {
			$scope.isLoad = true;
			$timeout(function() {
				$scope.isLoad = false;
				$scope.$broadcast('scroll.infiniteScrollComplete');
			}, 1000);
		};

		//侧边菜单
		$scope.rightSideMenu = function() {
			$ionicSideMenuDelegate.toggleRight();
		};
		//查询
		$scope.doSearch = function() {
			$ionicSideMenuDelegate.toggleRight();

			search_store();
		};
		//取消
		$scope.doCancel = function() {
			$ionicSideMenuDelegate.toggleRight();
		};

		$rootScope.init_localtion = function() {
			var issue_type = null;
			if(Auth.check_loginInfo()) {
				$scope.data.isLogin = true;
				var Infos = Auth.get_loginInfo();
				if(Infos.user_type == 1) {
					$scope.data.isClient = true;
				}
				issue_type = Infos.store_issue;
			} else {
				$scope.data.isClient = true;
			}

			// 企业类型列表
			var issue_list = $scope.data.issue_list;
			if($scope.data.isClient) {
				issue_list.push({ "type": 4, "name": "加盟店" });
			} else if(issue_type == 1 || issue_type == 2) {
				issue_list.push({ "type": 3, "name": "授权中心" });
				// issue_list.push({ "type": 5, "name": "分仓" });
				issue_list.push({ "type": 4, "name": "加盟店" });
			} else if(issue_type == 3) {
				issue_list.push({ "type": 1, "name": "旗舰店" });
				// issue_list.push({ "type": 2, "name": "品牌运营商" });
				issue_list.push({ "type": 4, "name": "加盟店" });
			} else if(issue_type == 4) {
				issue_list.push({ "type": 3, "name": "授权中心" });
				// issue_list.push({ "type": 5, "name": "分仓" });
			}

			$scope.initRegionSelect(function() {
				$scope.initStoreCatSelect(function() {
					$scope.data.point = null;
					$scope.init_map(function() {
						//搜索
						search_store();
					});
				})
			});
		}

		// 地域初始化
		$scope.initRegionSelect = function(cb) {
			// if (GLOBLE.region) {
			// 	$scope.data.store_region.data = GLOBLE.region;
			// 	cb && cb();
			// 	return;
			// }

			if($scope.data.store_region.data.list1 &&
				$scope.data.store_region.data.list1.length > 0) {
				cb && cb();
				return;
			}

			try {
				// 初始化地区三级联动
				GoRegion.init('', function(success, initdata, packageName) {
					if(!success) {
						return;
					}
					$scope.data.store_region.data = initdata;

				}, function() {

				}, function() {
					cb && cb();
				})
			} catch(ex) {
				cb && cb();
			}
		}

		function search_store() {
			var Infos = Auth.get_loginInfo() || {};
			// 保存
			Findus.get_home({
				'is_member_map': $scope.data.isMemberMap ? 'is_member_map' : '',
				'region_id': $scope.data.area,
				'brand': $scope.data.brand,
				'store_issue': $scope.data.store_issue,
				'store_cat': $scope.data.goods_cat,
				'store_name': ($scope.data.store_name || '').trim(),
				'current_lat': $scope.data.point.lat,
				'current_lng': $scope.data.point.lng,
			}, function(res) {
				if(res.success != true) {
					GoDialog.toast(res.msg);
					return;
				}

				$scope.data.search_lng = res.result.current_lng;
				$scope.data.search_lat = res.result.current_lat;
				$scope.data.search_loc_name = res.result.current_loc_name;
				$scope.data.store_list = res.result.storelist.list || [];
				$scope.data.page_index = res.result.storelist.page_index;
				$scope.data.page_count = res.result.storelist.page_count;

				$scope.data.location_rs.address = $scope.data.search_loc_name;

				if($scope.data.store_list.length >= 0) {
					$scope.show_store();
				} else {
					$scope.init_map(null, true);
				}

			})
		}

		// 生成分类值
		function setStoreCat() {
			var sc = $scope.data.store_cat.cats;
			var store_cat = '';

			var cat = sc[0];
			var name = '';
			var value = '';
			for(var i = 1; i <= 3; i++) {
				var v = cat['value' + i];
				if(v) {
					var l = cat['list' + i]
					for(var j = 0; j < l.length; j++) {
						if(v == l[j].id) {
							if(name) name += '/';
							name += l[j].text;
							value = v;
							break;
						}
					}
				}
			}

			if(value) {
				$scope.data.goods_cat = name + ':' + value;
			} else {
				$scope.data.goods_cat = '';
			}
		}

		// 分类三级联动下拉框发生变动
		$scope.change_Catselect = function(lvl) {
			if(lvl == 3) {
				setStoreCat();
				return;
			}

			var store_cat = $scope.data.store_cat;
			var cat = store_cat.cats[0];
			var selected_id = cat['value' + lvl];
			GoBrandCat.get_nextlvl({ cat_id: selected_id }, lvl, cat, null, null, function() {
				// done
				setStoreCat()
			})
		}

		// 分类初始化
		$scope.initStoreCatSelect = function(cb) {
			// if (GLOBLE.store_cat) {
			// 	$scope.data.store_cat = GLOBLE.store_cat;
			// 	cb && cb();
			// 	return; 
			// }

			if($scope.data.store_cat.cats &&
				$scope.data.store_cat.cats[0] &&
				$scope.data.store_cat.cats[0].list1 &&
				$scope.data.store_cat.cats[0].list1.length > 0) {
				cb && cb();
				return;
			}

			try {
				var store_cat = "";
				var inputdata = [store_cat];

				// 初始化地区三级联动
				GoBrandCat.init({ inputdata: inputdata }, function(success, initdata) {
					if(!success) {
						return;
					}
					if(!initdata || initdata.length == 0){
						return;
					}
					$scope.data.store_cat = initdata[0];

				}, function() {

				}, function() {
					setStoreCat();
					cb && cb();
				})
			} catch(ex) {
				cb && cb();
			}

		}

		$scope.change_Regionselect = function(lvl) {
			var sr = $scope.data.store_region;
			var selected_id = sr.data['value' + lvl];
			$scope.data.area = selected_id;

			if(lvl == 1 && $scope.data.isMemberMap ||
				lvl == 3) {
				return;
			}

			GoRegion.get_nextlvl(selected_id, lvl, sr.data, null, null, function() {})
		}

		$scope.show_store = function() {
			var list = [];
			for(var i = 0; i < $scope.data.store_list.length; i++) {
				var s = $scope.data.store_list[i];

				list.push({
					content: s.store_name,
					lng: s.company_lng,
					lat: s.company_lat,
				});

				var area = s.company_area || '';
				var index = area.indexOf(':');
				if(index > 0) {
					area = area.substring(index + 1);
					index = area.indexOf(':');
					if(index >= 0) {
						area = area.substring(0, index);
						area = area.replace(new RegExp(/(\/)/g), ' ')
					}
				}
				s.company_area_text = area;

				var issue = '';
				if(s.issue_type == 1) {
					issue = '旗舰店';
				} else if(s.issue_type == 2) {
					issue = '品牌运营商';
				} else if(s.issue_type == 3) {
					issue = '授权中心';
					if(s.is_warehouse == 'Y') {
						issue = '分仓';
					}
				} else if(s.issue_type == 4) {
					issue = '加盟店';
				}
				s.issue_type_text = issue;

				s.distance_show = null;
				if(s.distance) {
					var distance = s.distance / 1000;
					if(!isNaN(distance)) {
						s.distance_show = distance.toFixed(1);
					}
				}
			}

			if(list.length == 0) {
				list.push({
					content: $scope.data.search_loc_name,
					lng: $scope.data.search_lng,
					lat: $scope.data.search_lat
				});
			}

			GoMap.set_location("container_" + $scope.data.container_stamp, list);
		}

		$scope.goto_store = function(store_id) {
			GoPage.go_states("first", {
				store_id: store_id
			});
		}
		$scope.doSelectValue1 = function(){
			//id是值 name是显示
			GoDialog.showSelect("分类",$scope.data.store_cat.cats[0].list1,$scope.data.store_cat.cats[0].value1_select,function(data){
				$scope.data.store_cat.cats[0].value1 = data.id;
				$scope.data.store_cat.cats[0].value1_select = data;
				$scope.change_Catselect(1);
			});
		}
		$scope.doSelectValue2 = function(){
			//id是值 name是显示
			GoDialog.showSelect("分类",$scope.data.store_cat.cats[0].list2,$scope.data.store_cat.cats[0].value2_select,function(data){
				$scope.data.store_cat.cats[0].value2 = data.id;
				$scope.data.store_cat.cats[0].value2_select = data;
				$scope.change_Catselect(2);
			});
		}
		$scope.doSelectValue3 = function(){
			//id是值 name是显示
			GoDialog.showSelect("分类",$scope.data.store_cat.cats[0].list3,$scope.data.store_cat.cats[0].value3_select,function(data){
				$scope.data.store_cat.cats[0].value3 = data.id;
				$scope.data.store_cat.cats[0].value3_select = data;
				$scope.change_Catselect(3);
			});
		}
		$scope.doSelectType = function(){
			var list = new Array();
			$scope.data.issue_list.forEach(obj => {
				if(obj.id == undefined)
				obj.id = obj.type;
				list.push(obj);
			});
			//id是值 name是显示
			GoDialog.showSelect("类型",list,$scope.data.store_issue_select,function(data){
				$scope.data.sstore_issue = data.type;
				$scope.data.store_issue_select = data;
			});
		}
		$scope.doSelectProvince = function(){
			//id是值 name是显示
			GoDialog.showSelect("请选择省份",$scope.data.store_region.data.list1,$scope.data.store_region.data.value1_select,function(data){
				$scope.data.store_region.data.value1 = data.id;
				$scope.data.store_region.data.value1_select = data;
				$scope.change_Regionselect(1);
			});
		}
		$scope.doSelectCity = function(){
			//id是值 name是显示
			GoDialog.showSelect("请选择城市",$scope.data.store_region.data.list2,$scope.data.store_region.data.value2_select,function(data){
				$scope.data.store_region.data.value2 = data.id;
				$scope.data.store_region.data.value2_select = data;
				$scope.change_Regionselect(2);
			});
		}
		$scope.doSelectDistrict = function(){
			//id是值 name是显示
			GoDialog.showSelect("请选择区/县",$scope.data.store_region.data.list3,$scope.data.store_region.data.value3_select,function(data){
				$scope.data.store_region.data.value3 = data.id;
				$scope.data.store_region.data.value3_select = data;
				$scope.change_Regionselect(3);
			});
		}
	}

	controller.$inject = ['$scope','$rootScope', '$stateParams', 'Findus', 'GoDialog', '$window', '$timeout', '$ionicSideMenuDelegate', '$ionicLoading', 'Auth', 'GoRegion', 'GoBrandCat', 'GoMap', 'GoPage', 'GoWapAuth'];

	return app.registerController("findusctrl", controller);
});